package com.zktravel.aop;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zktravel.core.session.SessionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Sets;
import com.zktravel.core.vo.Result;
import com.zktravel.enums.CodeEnum;
import com.zktravel.util.WebUtils;

public class ReqHeaderInterceptor implements HandlerInterceptor {
    private static Logger logger = LoggerFactory.getLogger(ReqHeaderInterceptor.class);

    public final static String DEFAULT_SKIP_NOLOGIN_URL = "/login, /login.*, /login/*, /open/**/*, /cache/*, "
            + "/swagger-*, /swagger-*/**/*, /webjars/**/*, /v2/*, /chk.html, /api/**/*";
    private Set<String> skipNoLoginUrls = Sets.newHashSet();
    private PathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        addToUrlSet(DEFAULT_SKIP_NOLOGIN_URL, skipNoLoginUrls);
        // 获得在下面代码中要用的request,response,session对象
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        // 获得用户请求的URI
        String uri = req.getRequestURI();// 访问全路径
        String contextPath = req.getContextPath();// 容器名称
        String path = uri.replace(contextPath, "");// 本次访问路径

        // 无需过滤的请求
        for (String url : skipNoLoginUrls) {
            if (pathMatcher.match(url, path)) {
                SessionContext.clear();
                logger.trace("跳过无需sid&uid的URL：" + url);

                return true;
            }
        }

        String sid = req.getHeader("x-shop-sid");
        String uid = req.getHeader("x-shop-uid");
        logger.info("uid[" + uid + "] sid[" + sid + "] url[" + path + "]");

        if (StringUtils.isEmpty(sid) || StringUtils.isEmpty(sid)) {
            String json = JSON.toJSONString(new Result(CodeEnum.ERROR_UID));
            WebUtils.writeJson(json, res);
            return false;
        }
        // 获取用户信息
//        UserInfo userInfo = this.userService.getUserInfo(Long.parseLong(uid));
//        if (null == userInfo) {
//            SessionContext.clear();
//            String json = JSON.toJSONString(new Result(CodeEnum.ERROR_GET_USER_INFO));
//            WebUtils.writeJson(json, res);
//            return false;
//        }
//
//        userInfo.setShopId(Long.parseLong(sid));
        SessionContext.setUserId(Long.parseLong(uid));
        SessionContext.setShopId(Long.parseLong(sid));

        return true;
    }

    @Override
    public void postHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler,
            ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler,
            Exception ex) throws Exception {

    }

    private void addToUrlSet(String urls, Set<String> set) {
        if (StringUtils.hasText(urls) && set.size() <= 0) {
            for (String s : urls.split("[,]")) {
                if (StringUtils.hasText(s))
                    set.add(s.trim());
            }
        }
    }
}
